package com.hspedu.reflection;

import java.lang.reflect.Field;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/3/23
 * @time 17:47
 */
public class ReflectAccessProperty {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
        Class studentClass = Class.forName("com.hspedu.reflection.Student");
        Student student = (Student) studentClass.newInstance();
        Field age = studentClass.getField("age");
        age.set(student,88);
        System.out.println(student);
        Field name = studentClass.getDeclaredField("name");
        //必须要记得暴破
        name.setAccessible(true);
        name.set(null,"小明");
        System.out.println(student);
        //只有是静态属性才能使用null
        System.out.println("name = " + name.get(null));
        System.out.println("name = " + name.get(student));
    }

}

class Student {//类
    public int age;
    private static String name;

    public Student() {//构造器
    }

    @Override
    public String toString() {
        return "Student [age=" + age + ", name=" + name + "]";
    }
}